<?php
// +----------------------------------------------------------------------
// | Action: 系统登录控制器
// +----------------------------------------------------------------------
// | Author: chen <vd8888@126.com>
// +----------------------------------------------------------------------
// |   ToDo: 
// +----------------------------------------------------------------------
class LoginAction extends Action {
	/*代理商登录页面*/
	public function login(){
		trace($_SESSION,'Session["validcode"]');
		$this->display();
	}
	/*代理商登录页面验证码*/
	public function verify(){
		V('yanzhengma');    //直接调用V函数加验证码的name,即可输出验证码
	}
	/*代理商登录验证*/
	public function loginverify() {

		$agentname		=	I('username');
		$agentpassword	=	I('password');
		$verifycode		=	I('validcode');
		$hash			=	I('hash');
		$hashzhi			=	end($_SESSION['__hash__']);
		$hashkey		=	array_keys($_SESSION['__hash__'],$hashzhi);
		$sshash			=	md5(md5("$hashkey[0]".'_'."$hashzhi"));
		if (empty ( $agentname )) {
			echo '{"status":"error","errMsg":"用户名不能为空！"}';
			die();
		} elseif (empty ( $agentpassword)) {
			echo '{"status":"error","errMsg":"密码不能为空！"}';
			die();
		} elseif (empty( $verifycode )) {
			echo '{"status":"error","errMsg":"验证码不能为空！"}';
			die();
		}elseif (md5($verifycode) != $_SESSION['yanzhengma']){
			echo '{"status":"error","errMsg":"验证码错误!"}';
			die();
		}elseif ($sshash != $hash ){
			echo '{"status":"error","errMsg":"令牌错误!"}';
			die();
		}

		$agent=M('Proxy');
		$agentinfo['username']=$agentname;
		$agentinfo['password']=md5($agentpassword);
		$result=$agent->where($agentinfo)->find();		
		
		if (!empty($result['username'])){
			
			/*判断代理商是否已经激活或限制登录*/
			if ($result["isactive"] == 0 || $result["isactive"] =='') {
				echo '{"status":"error","errMsg":"此账号尚未激活，经联系客服！"}';
				die();
			}
			
			/*信息正常，记录本次登录信息*/
			$ip = get_client_ip();
	        $data['loginip'] = $ip;
	        $data['logincount'] = array('exp', '(logincount+1)');
	        $data['logintime'] = date("Y-m-d H:i:s");
	        $agent->where($agentinfo)->save($data);

			//记录登陆日志
	        $log = M("log");
	        $clientip = $ip;
	        $log->ip = $clientip;
	        import('ORG.Net.IpLocation'); // 导入IpLocation类
	        $Ip = new IpLocation(); // 实例化类
	        $location = $Ip->getlocation($clientip); // 获取某个IP地址所在的位置
	        $log->username = $agentname;
	        $log->address = $location['area'];
	        $log->addtime = date("Y-m-d H:i:s");
	        $log->loginfo = "代理商" . $agentname. "登录";
	        $log->logtype = 1;
	        $log->add();
			/*把当前账户，写到代理商session，并输出正常信息*/
			$_SESSION["agent"]['username']=$agentname;
			echo '{"status":"success","errMsg":"true"}';
				
		}else {
				
			echo '{"status":"error","errMsg":"账号信息验证不通过!"}';
				
		}
	}
	/*代理商退出系统*/
	public function logout() {
		session_destroy();//干掉所有session
		$url = U('__ROOT__/Login/login');
		redirect($url);
	}
}